package admin;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;

import DB.DB_connection_pool;

public class Admin_add extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		JSONObject jsonObj = new JSONObject();
		
		String admin_account = request.getParameter("admin_account");    //管理员账户
		String admin_password = request.getParameter("admin_password");    //管理员密码
		String admin_nickname = request.getParameter("admin_nickname");   //管理员昵称
		int super_jurisdiction = Integer.parseInt(request.getParameter("super_jurisdiction")); //超级权限
		int user_management_jurisdiction = Integer.parseInt(request.getParameter("user_management_jurisdiction"));   //用户管理权限
		int device_management_jurisdiction = Integer.parseInt(request.getParameter("device_management_jurisdiction"));   //设备管理权限
		int basic_jurisdiction = Integer.parseInt(request.getParameter("basic_jurisdiction"));   //基础权限
		
		String insert_sql = "insert into admin_login(admin_account,admin_password,admin_nickname,super_jurisdiction,user_management_jurisdiction,device_management_jurisdiction,basic_jurisdiction) values(?,?,?,?,?,?,?)";
		
		if((int)(request.getSession().getAttribute("super_jurisdiction")) == 1){
		try {
			Connection conn = DB_connection_pool.data_pool.getConnection();
			PreparedStatement ps_insert = conn.prepareStatement(insert_sql);
			ps_insert.setString(1, admin_account);
			ps_insert.setString(2, admin_password);
			ps_insert.setString(3, admin_nickname);
			ps_insert.setInt(4, super_jurisdiction);
			ps_insert.setInt(5, user_management_jurisdiction);
			ps_insert.setInt(6, device_management_jurisdiction);
			ps_insert.setInt(7, basic_jurisdiction);
			ps_insert.executeUpdate();
			
			jsonObj.put("result", true);
		} catch (SQLException e) {
			jsonObj.put("result", false);
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		}else{
			jsonObj.put("result", false);
		}
		out.print(jsonObj.toString());
		
	}

}
